/**
 顺序打印-进阶版
 */



import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class demo1 {

    private static final Lock lock = new ReentrantLock();
    private static final Condition conditionA = lock.newCondition();
    private static final Condition conditionB = lock.newCondition();
    private static final Condition conditionC = lock.newCondition();
    private static volatile int state = 0;

    public static void main(String[] args) {
        Thread threadA = new Thread(new PrintThread("A", 0, conditionA, conditionB));
        Thread threadB = new Thread(new PrintThread("B", 1, conditionB, conditionC));
        Thread threadC = new Thread(new PrintThread("C", 2, conditionC, conditionA));

        threadA.start();
        threadB.start();
        threadC.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        lock.lock();
        try {
            state = 0;
            conditionA.signal();
        } finally {
            lock.unlock();
        }
    }

    static class PrintThread implements Runnable {
        private String content;
        private int targetState;
        private Condition currentCondition;
        private Condition nextCondition;

        public PrintThread(String content, int targetState, Condition currentCondition, Condition nextCondition) {
            this.content = content;
            this.targetState = targetState;
            this.currentCondition = currentCondition;
            this.nextCondition = nextCondition;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (state % 3 != targetState) {
                        currentCondition.await();
                    }
                    System.out.print(content);
                    state++;
                    nextCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();



                }
            }
        }
    }
}

